import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserSession } from '../entities/user-session.entity';

@Injectable()
export class UserAnalyticsService {
  constructor(
    @InjectRepository(UserSession)
    private repo: Repository<UserSession>,
  ) {}
  
  async getActiveUsersLast24h() {
    const start = new Date(Date.now() - 24 * 3600 * 1000);
    return this.repo
      .createQueryBuilder()
      .select("DATE_FORMAT(loginAt, '%Y-%m-%d %H:00:00')", 'hour')
      .addSelect('COUNT(*)', 'count')
      .where('loginAt >= :start', { start })
      .groupBy('hour')
      .orderBy('hour', 'ASC')
      .getRawMany();
  }
}